/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "rng.h"
#include "stm32wlxx_hal.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

COM_InitTypeDef BspCOMInit;
uint32_t pulse_start_tick = 0, pulse_end_tick = 0;
uint8_t gv_bp_flag = 0;

/* USER CODE BEGIN PV */
volatile uint8_t flow_direction = 0;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void delay_us(uint32_t us);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  uint32_t positive_pulse_count = 0;
  uint32_t reverse_pulse_count = 0;
  uint32_t accumulate_pulse_count = 0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM1_Init();
  MX_TIM2_Init();
  MX_RNG_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Initialize leds */
  BSP_LED_Init(LED_BLUE);
  BSP_LED_Init(LED_GREEN);
  BSP_LED_Init(LED_RED);

  /* Initialize USER push-button, will be used to trigger an interrupt each time it's pressed.*/
  BSP_PB_Init(BUTTON_SW1, BUTTON_MODE_EXTI);
  BSP_PB_Init(BUTTON_SW2, BUTTON_MODE_EXTI);
  BSP_PB_Init(BUTTON_SW3, BUTTON_MODE_EXTI);

  /* Initialize COM1 port (115200, 8 bits (7-bit data + 1 stop bit), no parity */
  BspCOMInit.BaudRate   = 115200;
  BspCOMInit.WordLength = COM_WORDLENGTH_8B;
  BspCOMInit.StopBits   = COM_STOPBITS_1;
  BspCOMInit.Parity     = COM_PARITY_NONE;
  BspCOMInit.HwFlowCtl  = COM_HWCONTROL_NONE;
  if (BSP_COM_Init(COM1, &BspCOMInit) != BSP_ERROR_NONE)
  {
    Error_Handler();
  }

  /* USER CODE BEGIN BSP */

  /* -- Sample board code to send message over COM1 port ---- */
  printf("Welcome to STM32 world !\n\r");

  /* -- Sample board code to switch on leds ---- */
  BSP_LED_On(LED_BLUE);
  BSP_LED_On(LED_GREEN);
  BSP_LED_On(LED_RED);

  /* USER CODE END BSP */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {

    if (gv_bp_flag == 1) {
      flow_direction = 0;
      gv_bp_flag = 0;
    } else if (gv_bp_flag == 2) {
      flow_direction = 1;
      gv_bp_flag = 0;
    } else if (gv_bp_flag == 3) {
      /* nothing */
    } else {
      continue;
    }
    
    while (HAL_GetTick() < pulse_end_tick + PULSE_WIDTH_MS) {
      continue;
    }

    pulse_start_tick = HAL_GetTick();
    /* NOTE: actual pulse period ~31ms */
    if (flow_direction == 0) {
      HAL_GPIO_WritePin(PULSE_OA_GPIO_Port, PULSE_OA_Pin, GPIO_PIN_SET);
      // HAL_TIM_Base_Start_IT(&htim1);
      HAL_TIM_Base_Start(&htim1);
      __HAL_TIM_CLEAR_IT(&htim1, TIM_IT_UPDATE);
      __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE);
      delay_us(PULSE_WIDTH_MS * 1000 / 2);
      HAL_GPIO_WritePin(PULSE_OB_GPIO_Port, PULSE_OB_Pin, GPIO_PIN_SET);
      HAL_TIM_Base_Start(&htim2);
      __HAL_TIM_CLEAR_IT(&htim2, TIM_IT_UPDATE);
      __HAL_TIM_ENABLE_IT(&htim2, TIM_IT_UPDATE);
      positive_pulse_count++;
      accumulate_pulse_count++;
    } else {
      HAL_GPIO_WritePin(PULSE_OB_GPIO_Port, PULSE_OB_Pin, GPIO_PIN_SET);
      HAL_TIM_Base_Start(&htim2);
      __HAL_TIM_CLEAR_IT(&htim2, TIM_IT_UPDATE);
      __HAL_TIM_ENABLE_IT(&htim2, TIM_IT_UPDATE);
      delay_us(PULSE_WIDTH_MS * 1000 / 2);
      HAL_GPIO_WritePin(PULSE_OA_GPIO_Port, PULSE_OA_Pin, GPIO_PIN_SET);
      HAL_TIM_Base_Start(&htim1);
      __HAL_TIM_CLEAR_IT(&htim1, TIM_IT_UPDATE);
      __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE);
      reverse_pulse_count++;
      accumulate_pulse_count--;
    }
    
    /* uart poll print may increase pulse interval, todo: use dma print */
    if (flow_direction == 0) {
      printf("P: %4ld, T: %4ld\n", positive_pulse_count, accumulate_pulse_count);
    } else {
      printf("R: %4ld, T: %4ld\n", reverse_pulse_count, accumulate_pulse_count);
    }
    
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
  RCC_OscInitStruct.LSIDiv = RCC_LSI_DIV1;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure the SYSCLKSource, HCLK, PCLK1 and PCLK2 clocks dividers
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK3|RCC_CLOCKTYPE_HCLK
                              |RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1
                              |RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.AHBCLK3Divider = RCC_SYSCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

void delay_us(uint32_t us)
{
    uint32_t last, now, reload, tick, sub;
    last = SysTick->VAL;
    reload = SysTick->LOAD;
    tick = SystemCoreClock / 1000000UL * us;
    sub = 0;

    while (tick > sub)
    {
        tick -= sub;
        now = SysTick->VAL;
        sub = last >= now ? last - now : reload + last - now;
        last = now;
    }
}


void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htimx)
{
  if (htimx == &htim1) {
    HAL_TIM_Base_Stop(&htim1);
    HAL_GPIO_WritePin(PULSE_OA_GPIO_Port, PULSE_OA_Pin, GPIO_PIN_RESET);
  } else if (htimx == &htim2) {
    HAL_TIM_Base_Stop(&htim2);
    HAL_GPIO_WritePin(PULSE_OB_GPIO_Port, PULSE_OB_Pin, GPIO_PIN_RESET);
  } else {
    Error_Handler();
  }
  if ((int32_t)(pulse_start_tick - pulse_end_tick) > 0) {
    pulse_end_tick = HAL_GetTick();
  }
}

/* USER CODE END 4 */

/**
* @brief BSP Push Button callback
* @param Button Specifies the pressed button
* @retval None
*/
void BSP_PB_Callback(Button_TypeDef Button)
{
  switch(Button)
  {
    case BUTTON_SW1:
      gv_bp_flag = 1;
      break;
    case BUTTON_SW2:
      gv_bp_flag = 2;
      break;
    case BUTTON_SW3:
      gv_bp_flag = 3;
      break;
    default:
      break;
  }

}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
